﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using PathologicalGames;

namespace GameJam
{
	public class EnergySpawner : MonoBehaviour 
	{
		[SerializeField]
		private GameObject _prefab;
		[SerializeField]
		public string poolName = "Energy";
		SpawnPool _pool;

		[SerializeField]
		int _minGenarate = 1;
		[SerializeField]
		int _maxGenarate = 3;
		[SerializeField]
		float _interval = 4.0f;
		float _timer = 0.0f;

		[SerializeField]
		float _randomOffset = 0.4f;

		[SerializeField]
		List<Transform> _genaratePoints;

		bool _bStarted = false;
		public bool IsStarted {
			get { return _bStarted; }
			set{ _bStarted = value; }
		}

		static EnergySpawner _instance;
		public static EnergySpawner Instance{ get { return _instance;}}

		public int CurEnergyOnGround 
		{
			get { return _pool == null ? 0: _pool.Count;}
		}

		void Awake()
		{
			_instance = this;
		}

		// Use this for initialization
		void Start () 
		{
			SpawnPool _pool = PoolManager.Pools [this.poolName];
			if (_pool == null)
				_pool = PoolManager.Pools.Create (this.poolName);
		}

		void Update ()
		{
			if (!IsStarted)
				return;

			_timer += Time.deltaTime;

			if (_timer > _interval) {
				Generate ();
				_timer = 0.0f;
			}
		}

		public void Generate()
		{
			int allEnergies = GameCtrl.Instance.AllEnergyInGame();
			int maxEnergies = GameCtrl.Instance.MaxEnergyInGame();

			if (allEnergies >= maxEnergies)
				return;

			//_pool.Count;
			int count = Random.Range (_minGenarate, _maxGenarate);

			if (allEnergies + count > maxEnergies)
				count = maxEnergies - allEnergies;

			for (int i = 0; i < count; ++i)
			{
				int index = Random.Range (0, _genaratePoints.Count);
				Vector3 pos = _genaratePoints [index].position;
				pos.x += Random.Range (-_randomOffset, _randomOffset);
				pos.y += Random.Range (-_randomOffset, _randomOffset);
				Spawn (pos);
			}
		}

		public Transform Spawn(Vector3 pos)
		{
			_pool = PoolManager.Pools [this.poolName];
			Transform prefab_trans = _pool.Spawn (_prefab);
			prefab_trans.position = pos;

			return prefab_trans;
		}

		public void Despawn(EnergyPoint energy)
		{
			if (energy.gameObject.activeSelf)
				_pool.Despawn (energy.transform);
		}

        public void DespawnAll()
        {
            _pool.DespawnAll();

        }

        public void ReStartGame()
        {
            _pool.DespawnAll();
            IsStarted = false;
        }
	}
}
